package com.webrtc.config.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author liuzhiqiang
 */
@RestController
@CrossOrigin
@Slf4j
public class HttpController {

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 登录
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/login")
    public TargetUser login(@RequestBody JSONObject jsonObject) {
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");
        if (currentUser != null) {
            httpServletRequest.getSession().removeAttribute("targetUser");
            LoginResources.loginUser.remove(currentUser.getUserId());
        }


        String username = jsonObject.getString("username");
        if (StringUtils.isEmpty(username)) {
            username = UUID.randomUUID().toString();
        }
        TargetUser targetUser = new TargetUser();
        targetUser.setUsername(username);
        targetUser.setUserId(UUID.randomUUID().toString());
        targetUser.setTime(1L);
        httpServletRequest.getSession().setAttribute("targetUser", targetUser);
        LoginResources.addUser(targetUser.getUserId(), targetUser);
        // 告诉所有的在线用户 如果您准备好的媒体流 请跟我发送一个offer事件
        Map<String, TargetUser> map = LoginResources.loginUser;
        map.forEach((k, user) -> {
            // 构建消息体
            JSONObject message = new JSONObject();
            message.put("sender", targetUser.getUserId());
            message.put("data", "requestOffer");
            user.getJsonObject().add(message);
        });
        return targetUser;
    }

    /**
     * 获取在线用户
     *
     * @return
     */
    @GetMapping("/getOnlineUser")
    public List<JSONObject> getOnlineUser() {
        Map<String, TargetUser> map = LoginResources.loginUser;
        List<JSONObject> userList = new ArrayList<>();
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");
        map.forEach((k,targetUser) -> {
            if (!StringUtils.equals(k, currentUser.getUserId())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId", targetUser.getUserId());
                jsonObject.put("username", targetUser.getUsername());
                jsonObject.put("seatNum", targetUser.getSeatNum());
                userList.add(jsonObject);
            }

        });

        return userList;
    }

    /**
     * 发送 消息
     * 请求和指定客户端建立连接
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/sendMessage")
    public JSONObject sendMessage(@RequestBody JSONObject jsonObject) {
        // 当前登录用户
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");

        // 构建消息体
        JSONObject message = new JSONObject();

        message.put("sender", currentUser.getUserId());
        message.put("data", jsonObject.getJSONObject("data"));

        TargetUser targetUser = LoginResources.getUser(jsonObject.getString("recipient"));
        JSONObject result = new JSONObject();
        if (targetUser != null) {
            targetUser.getJsonObject().add(message);
            result.put("data", "已发送");
            return result;
        } else {
            result.put("data", "对方不在线");
            return result;
        }
    }


    /**
     * 获取消息
     *
     * @return
     */
    @GetMapping("getMessage")
    public JSONObject getMessage() {
        // 当前登录用户
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");
        if (currentUser != null) {
            currentUser.setTime(1L);

            List<JSONObject> list = currentUser.getJsonObject();
            if (list != null && list.size() > 0) {
                JSONObject jsonObject = list.get(0);
                list.remove(0);
                return jsonObject;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @PostMapping("setSeatNum")
    public JSONObject setSeatNum(String seatNum) {
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");
        currentUser.setSeatNum(seatNum);
        JSONObject result = new JSONObject();
        result.put("data","已设置");
        return result;
    }

    @GetMapping("/getUser")
    public JSONObject getUser(String userId) {
        TargetUser targetUser = LoginResources.getUser(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", targetUser.getUserId());
        jsonObject.put("username", targetUser.getUsername());
        jsonObject.put("seatNum", targetUser.getSeatNum());
        return jsonObject;
    }

    @PostMapping("/exit")
    public JSONObject exit() {
        TargetUser currentUser = (TargetUser) httpServletRequest.getSession().getAttribute("targetUser");
        LoginResources.loginUser.remove(currentUser.getUserId());
        httpServletRequest.getSession().removeAttribute("targetUser");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data","退出成功");
        return jsonObject;
    }


    @PostMapping("/webHook")
    public JSONObject webHook(@RequestBody JSONObject jsonObject) {
        log.info("webHook结果[{}]", jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("code", 200);
        jsonObject1.put("msg", "ok");
        jsonObject1.put("time", System.currentTimeMillis());

        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("api_response_status", true);
        jsonObject3.put("dataResult",JSONObject.toJSONString(jsonObject));
        jsonObject2.put("context", jsonObject3);


        jsonObject1.put("data", jsonObject2);
        return jsonObject1;
    }
}
